﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Portal.Api;
using System.Xml;
using Portal.Modules.FileBrowser;
using Portal.Api.FeedProvider;
using Portal.FileSystemData;

/// <summary>
/// Summary description for FileBrowserRssFeed
/// </summary>
[FeedDataProvider("FB", "FileBrowser")]
public class FileBrowserRssFeed : IFeedDataProvider
{

  private ModuleDocument _moduleDocument;

  public FileBrowserRssFeed()
  {
  }


  #region IRssDataProvider Members

  /// <summary>
  /// Adds the data of a module to the rss feed.
  /// </summary>
  /// <param name="request">The request for the rss feed.</param>
  /// <param name="response">The response for the feed data.</param>
  /// <param name="document">The module document instance</param>
  public void ProvideFeed(System.Web.HttpRequest request, System.Web.HttpResponse response, ModuleDocument document)
  {
    _moduleDocument = document;

    RssFeed rssFeed = null;

    try
    {
      // Read the data.
      ModuleConfig cfg = (ModuleConfig)document.ReadConfig(typeof(ModuleConfig));
      if (cfg == null)
        cfg = new ModuleConfig();
      ConfigAgent cfgAgent = new ConfigAgent(cfg);

      // Initialize Response as a rssFeed.
      response.ContentType = "text/xml; charset=utf-8";
      rssFeed = new RssFeed(response.OutputStream, request.Url.ToString());

      if (cfgAgent.Config.EnableRssFeed)
      {
        rssFeed.GuidIsPermaLink = false;

        // Write Header Data.
        rssFeed.AddTitle(cfg.RssFeedTitle);
        rssFeed.AddUrl(Config.GetAbsoluteUrl());
        rssFeed.AddDescription(cfg.RssFeedDescription);
        rssFeed.AddLanguage(System.Threading.Thread.CurrentThread.CurrentUICulture.Name);
        rssFeed.AddGenerator("Personal .NET Portal");
        rssFeed.AddTimeToLive(cfg.RssFeedTimeToLive);

        // Write Detail data.
        AddItems(rssFeed, cfgAgent.RootDirectory);
      }
      else
        response.StatusCode = 404;  // Not found.
    }
    finally
    {
      if(rssFeed != null)
        rssFeed.Close(); 
    } 
  }

  /// <summary>
  /// Add the items recursive.
  /// </summary>
  /// <param name="rssFeed"></param>
  /// <param name="directory"></param>
  private void AddItems(RssFeed rssFeed, DirectoryWrapper directory)
  {
    if(directory.FileCount > 0)
      rssFeed.AddItems(directory.Files, ExtendItem);  

    foreach (var subDir in directory.SubDirectories)
    {
      AddItems(rssFeed, subDir);
    }
  }

  /// <summary>
  /// Add detaildata to the item, that are not provided through the FileWrapper-Class.
  /// </summary>
  /// <param name="item"></param>
  /// <param name="rssFeed"></param>
  private void ExtendItem(object item, RssFeed rssFeed)
  {
    FileWrapper fileWrap = item as FileWrapper;
    if (fileWrap == null)
      throw new InvalidOperationException("Not of type FileWrapper");

    // Add the url.
    string downloadUrl = Config.GetAbsoluteUrl("~/Download.aspx");
    downloadUrl += string.Format("?Type=FileBrowser&Module={0}&Att=1&Rss=1&File={1}", 
                                 HttpUtility.UrlEncode(_moduleDocument.ModuleRef),
                                 HttpUtility.UrlEncode(fileWrap.VirtualPath)); 
    rssFeed.WriteItemElement(ItemElementType.link, downloadUrl);
    rssFeed.WriteItemEnclosure(downloadUrl, fileWrap.FileSize, fileWrap.MimeType);
  }

  #endregion
}
